<template>
  <page-wrap  :loading="loading">
    <div class="certificate-container">
      <div class="tabs-list-box">
        <div
          class="list-item"
          v-for="(tab, index) in tabs"
          :key="index"
          :class="['tab-button', { active: activeTab === index }]"
          @click="setActiveTab(index)"
        >
          {{ tab.label }}
        </div>
      </div>
      <div v-show="!scanning">
        <div class="certificate-header">请扫描或者输入券码核销</div>
        <div class="certificate-main" @click="getCameras"></div>
      </div>
      <div v-show="scanning" class="container">
        <div id="reader"></div>
      </div>
      <div class="roomName">房台号：{{ route.query.roomName }}</div>
      <div class="certificate-footer" @click="stop">
        <input
          type="text"
          placeholder="请输入优惠券券码"
          class="certificate-footer-input"
          id="inputId"
        />
        <z-button
          @click="onSubmit"
          style="
            font-size: 16px;
            font-family: PingFang SC;
            font-weight: 500;
            margin: 5px;
            line-height: 16px;
            color: #260c04;
            border-radius: 3px;
            white-space: pre;
          "
        >
          确认券码
        </z-button>
      </div>
    </div>
    <div class="change-type" @click="changType">切换成正常模式</div>
    <z-dialog
      v-model:show="confirmSignshow"
      content="是否确认使用？"
      @confirm="onConfirmSign"
    ></z-dialog>
  </page-wrap>
   <!-- 套餐弹窗 -->
   <ComboSelect v-model:show="comboSelectShow" :data="comboData" :isBanAddAll="true" @join="onJoinCombo"></ComboSelect>
   <z-popup v-model:show="comSelectShow" title="套餐选择">
    <div class="popup-block" style="min-width: 300px">
      <div class="popup-block-main">
       <div class="main-item" :class="comSelectActive == k ? 'select':'' " v-for="(v,k) in comSelectList" :key="k" @click="selectCom(k)">
           {{ v.goodsName }}
       </div>
      </div>
      <div class="popup-block-footer">
        <z-button-group class="button-group">
          <z-button @click="comSelectShow = false" plain style="margin-right: 12px">取消</z-button>
          <z-button @click="comSelectComfirm">确定</z-button>
        </z-button-group>
      </div>
    </div>
  </z-popup>
</template>
<script setup>
import useConfigStore from '@/store/config'
import { calculateOrderQty } from '@/lib/util.js'
import { ZButton } from "@/components/Button";
import { Html5Qrcode } from "html5-qrcode";
import { showToast } from "vant";
import Api from "@/api";
import _ from 'lodash'

const defutImage = ref('https://oss.jtmckj.com/wmp/qnjg/signin/defutImage.png')
const scanning = ref(false);
const cameraId = ref("");
const devicesInfo = ref("");
const html5QrCode = ref(null);
const configStore = useConfigStore()

import ls from '@/lib/ls'
// const result = ref('')

onMounted(() => {
  // getCameras()
});


const changType = ()=>{
  router.replace({path:'certificate', query: { ...route.query }})
}

onUnmounted(() => {
  stop();
});

const getCameras = () => {
  nextTick(() => {
    scanning.value = true;
  });
  Html5Qrcode.getCameras()
    .then((devices) => {
      console.log("摄像头信息", devices);
      showToast("开启摄像头中，请稍等");
      if (devices && devices.length) {
        // 如果有2个摄像头，1为前置的
        if (devices.length > 1) {
          cameraId.value = devices[1].id;
        } else {
          cameraId.value = devices[0].id;
        }
        devicesInfo.value = devices;
        // start开始扫描
        start();
      }
    })
    .catch((err) => {
      // handle err 
      console.log("获取设备信息失败", err); // 获取设备信息失败
      showToast("摄像头权限被拒绝，请在浏览器设置中重新授权或重新退出登录"); 
    });
};
const start = () => {
  html5QrCode.value = new Html5Qrcode("reader");
  console.log("html5QrCode", html5QrCode);

  html5QrCode.value
    .start(
      cameraId.value,
      {
        fps: 1, // 设置每秒多少帧
        qrbox: { width: 250, height: 250 }, // 设置取景范围
      },
      (decodedText, decodedResult) => {
        console.log("扫描的结果", decodedText, decodedResult);
        showToast("扫描的结果", decodedText, decodedResult);
        // result.value = decodedText
        scanning.value = false;
        let inputElement = document.getElementById("inputId");
        inputElement.value = decodedText;
        onSubmit();
        if (decodedText) {
          stop();
        }
      },
      (errorMessage) => {
        // showToast('暂无扫描结果')
        console.log("暂无扫描结果", errorMessage);
      }
    )
    .catch((err) => {
      scanning.value = false;
      console.log(`Unable to start scanning, error: ${err}`);
    });
};
const stop = () => {
  if (!html5QrCode.value) return;
  html5QrCode.value
    .stop()
    .then((ignore) => {
      // QR Code scanning is stopped.
      console.log("QR Code scanning stopped.", ignore);
      // showToast('QR Code scanning stopped.')
    })
    .catch((err) => {
      // Stop failed, handle it.
      console.log("Unable to stop scanning.", err);
      showToast("Unable to stop scanning.");
    });
};

const router = useRouter();
const route = useRoute();
console.log(configStore.goodsList);
const confirmSignshow = ref(false);
const codeval = ref("");

const comSelectShow = ref(false) // 套餐选择弹窗
const comSelectList = ref([]) // 套餐选择数组
const comSelectActive = ref(0) // 选中的套餐

const onSubmit = () => {
  let inputValue = document.getElementById("inputId").value;
  codeval.value = document.getElementById("inputId").value;
  if (!inputValue) return;
  console.log("inputValue :>> ", inputValue);
  // router.push({
  //   path: '/open/certificate/ticketInfo',
  //   query: {
  //     code: inputValue,
  //     consumeCode: route.query.consumeCode,
  //     activeType:activeTab.value
  //   }
  // })

  if(activeTab.value == 1){ // 抖音券
    Api.Common.AppObjProcess.Do({
      functionName: "WriteOffTicketInfo",
      contentData: {tiktopCode:inputValue},
    })
    .then(res=>{
      console.log(res);
      
      // const result = configStore.goodsList
      // .filter(goods => goods.type == '2' && goods.goodsCode === res.GoodsCode); // 过滤符合条件的商品

      const result = configStore.goodsList.filter(goods => 
        goods.type === '2' && 
        res.list.some(item => item.GoodsCode === goods.goodsCode)
      );

      console.log(result); // 输出符合条件的商品数组
      if(result && result.length == 1){
        comSelectList.value = result
        resetCom(result[0]) // 处理套餐 
      }else if(result && result.length > 1){
        comSelectList.value = result
        comSelectShow.value = true
      }else{
        showToast("暂无商品");
      }

      
      
    })
  }

  
  if (activeTab.value == 0) { // 兑换券
    getTicketInfo();
  }

  if (activeTab.value == 2) { // 美团券
    Api.Common.AppObjProcess.Do({
      functionName: "MtWriteOffTicketInfo",
      contentData: {receiptCode:inputValue},
    })
    .then(res=>{
      console.log(res);
      // const result = configStore.goodsList
      // .filter(goods => goods.type == '2' && goods.goodsCode === res.GoodsCode); // 过滤符合条件的商品

      const result = configStore.goodsList.filter(goods => 
        goods.type === '2' && 
        res.list.some(item => item.GoodsCode === goods.goodsCode)
      );

      console.log(result); // 输出符合条件的商品数组
      if(result && result.length == 1){
        comSelectList.value = result
        resetCom(result[0]) // 处理套餐 
      }else if(result && result.length > 1){
        comSelectList.value = result
        comSelectShow.value = true
      }else{
        showToast("暂无商品");
      }

      
      
    })
  }
};

const selectCom = (e)=>{ // 选中套餐
  comSelectActive.value = e
}
const comSelectComfirm = ()=>{ // 选中套餐确认
  const res = comSelectList.value[comSelectActive.value]
  console.log(res);
  
  resetCom(res)
}


const comboSelectShow = ref(false) // 套餐弹窗
const ticketInfo = ref({});
const getTicketInfo = (params) => {
  const data = {
    memberTicketCode: codeval.value,
  };
  Api.Common.AppObjProcess.Do({
    functionName: "GetGoodsTicket", 
    contentData: data,
  })
    .then((res) => {
      
      console.log("获取券信息 res :>> ", res);
      ticketInfo.value = res;
      let obj = {
        list:[res]
      }
      console.log(configStore.goodsList);
      const result = configStore.goodsList.filter(goods => 
        obj.list.some(item => item.goodsCode === goods.goodsCode)
      );

      console.log(result); // 输出符合条件的商品数组
      if(result && result.length == 1){
        if(result[0].type == '1'){
          confirmSignshow.value = true;
        }else{
          comSelectList.value = result
          resetCom(result[0]) // 处理套餐 
        }
       
      }else if(result && result.length > 1){
        comSelectList.value = result
        comSelectShow.value = true
      }else{
        showToast("暂无商品");
      }
      // showToast('核销中，请稍等')
      // onConfirmSign()
    })
    .catch(() => {});
};

const comFlag = ref(false)
const loading = ref(false)
//二次确认
const onConfirmSign = () => {
  // if(comFlag.value){
  //   showToast("加载中");
  //   return
  // }
  loading.value = true
  comFlag.value = true
  // 抖音核销卷
  if (activeTab.value == 1) {
    const data = {
      tiktopCode: codeval.value,
      consumeCode: route.query.consumeCode,
      detail:comDetail.value,
      roomCode: route.query.roomCode,
    };
    Api.Common.AppObjProcess.Do({
      functionName: "WriteOffTicket",
      contentData: data,
    })
      .then((res) => {
        confirmSignshow.value = false
        console.log("使用券 res :>> ", res);
        showToast("使用成功");
        setTimeout(() => {
          loading.value = false
          comFlag.value = false
          router.push({
            path: "/open",
          });
        }, 2000);
      })
      .catch(() => {
        loading.value = false
        comFlag.value = false
      });
  } else if (activeTab.value == 0){
    const data = {
      memberTicketCode: codeval.value,
      consumeCode: route.query.consumeCode,
      memberCarCode: ticketInfo.value.memberCarCode,
      detail:comDetail.value,
      roomCode: route.query.roomCode,
    };
    Api.Common.AppObjProcess.Do({
      functionName: "UseGoodsTicket",
      contentData: data,
    })
      .then((res) => {
        confirmSignshow.value = false
       
        console.log("使用券 res :>> ", res);
        showToast("使用成功");
        setTimeout(() => {
          comFlag.value = false
          loading.value = false
          router.push({
            path: "/open",
          });
        }, 2000);
        
      })
      .catch(() => {
        comFlag.value = false
        loading.value = false
      });
  }else if (activeTab.value == 2){ // 美团券
    const data = {
      receiptCode: codeval.value,
      consumeCode: route.query.consumeCode,
      detail:comDetail.value,
      roomCode: route.query.roomCode,
    };
    Api.Common.AppObjProcess.Do({
      functionName: "MtWriteOffTicket",
      contentData: data,
    })
      .then((res) => {
        confirmSignshow.value = false
        
        console.log("使用券 res :>> ", res);
        
        showToast("使用成功");
        setTimeout(() => {
          comFlag.value = false
          loading.value = false
          router.push({
              path: "/open",
            });
          }, 2000);
        })
      .catch(() => {
        comFlag.value = false
        loading.value = false
      });
  }
};

// 定义 Tab 数据
const tabs = [{ label: "兑换卷" }, { label: "抖音卷" }, { label: "美团券" }];

// 设置当前选中的 Tab 索引
const activeTab = ref(0);

// 设置激活的 Tab
const setActiveTab = (index) => {
  activeTab.value = index;
};

const comboData = ref('')
const resetCom = (dyDetail)=>{
  comSelectShow.value = false
  const detail = dyDetail.priceList[0].detail
  console.log(detail);
  for (let i = 0; i < detail.length; i++) {
      const goodsDetail = detail[i].goodsDetail;
      detail[i].allNum = 0
      for (let j = 0; j < goodsDetail.length; j++) {
          const flavor = goodsDetail[j];
          flavor.isShowFlavor = true // 是否显示规格
          flavor.flavor = '' // 已选规格
          flavor.canPlus = false // 步进器是否可加
          flavor.stepNum = flavor.defaultQty // 步进器数量
          flavor.percentPrice = 0
          flavor.vipPercentPrice = 0
          flavor.isSelect = false // 是否选中
          flavor.choiceType = detail[i].choiceType
          flavor.operType = detail[i].operType
          // flavor.stepNum = '' 
          // console.log(flavor.goodsFlavor);
          if(flavor.goodsFlavor){
          if(flavor.goodsFlavor.includes('[')){
              flavor.goodsFlavor = JSON.parse(flavor.goodsFlavor)
          }
          for (let item of flavor.goodsFlavor) {
              item.active = false
              if(typeof item.FlavorStr == 'string'){
          
                  const str = item.FlavorStr;
                  
                  // 替换中文逗号为英文逗号
                  const normalizedStr = str.replace(/[，,]/g, ',');
                  // 使用英文逗号分隔字符串
                  const parts = normalizedStr.split(',');
                  // 将每个部分转换为对象
                  const result = parts.map(part => {
                      // 默认值
                      let uomName = part.trim();
                      let addprice = 0;
                      let select = false;
                      // 检查是否有#，设置select
                      if (uomName.includes('#')) {
                          select = true;
                          uomName = uomName.replace('#', '').trim();
                      }
                      // 检查是否有*，设置addprice
                      const match = uomName.match(/\*(\d+)$/);
                      if (match) {
                          addprice = parseInt(match[1], 10);
                          uomName = uomName.replace(match[0], '').trim();
                      }
                      return { uomName, addprice, select };
                  });
                  console.log(result);
        
                  item.sizeList = result
        
              }
          }
          console.log(flavor.goodsFlavor);
          
      }

      }
  }
  comboData.value = dyDetail
  comboSelectShow.value = true
}
const comDetail = ref('') // 处理过的套餐

const onJoinCombo = (product)=>{ // 套餐加入
  console.log(product);
   const arr = _.cloneDeep([product])
    if(arr.length <= 0){
        showToast('购物车为空')
        return
    }
    const newArr = []
    arr.forEach((obj) => {
        if (obj.hasOwnProperty('detail')) {
            obj.detail.forEach((detail) => {
                const newDetail = { ...detail, type: '3' };
                newArr.push(newDetail);
            });
            delete obj.detail;
        }
        newArr.push(obj);
    });
    newArr.reverse()
    comDetail.value = newArr.map((obj,k) => {
        const { num, defaultQty, type, flavor, goodsPriceCode , stepNum,choiceType,isSelect,operType } = obj
        const convertedObj = {
            ...obj,
        };
        convertedObj.itemCode = ''
        convertedObj.doType = 'add'
    
        if (flavor==undefined) {
            convertedObj.flavor = ''
        }
        if (goodsPriceCode==undefined) {
            convertedObj.goodsPriceCode = ''
        }
        if (num !== undefined) {
            convertedObj.orderQty = num;
            delete convertedObj.num;
        }
        if (defaultQty !== undefined) {
            convertedObj.orderQty = defaultQty;
            delete convertedObj.defaultQty;
        }
        if (stepNum !== undefined) {
            convertedObj.orderQty = stepNum;
            delete convertedObj.stepNum;
        }
        if(choiceType == '1' && isSelect == false && operType == '0'){ // choiceType == '1' 是挑选种类  isSelect false 未选中 operType == '1'固定项目 不能修改配置
            convertedObj.orderQty = 0
            delete convertedObj.choiceType;
            delete convertedObj.isSelect;
        }
        if (type=='0'||type=='1') {
            convertedObj.itemType = '1'
        }
        if (type === '2') {
            convertedObj.flavor = ''
            convertedObj.itemType = '2'
            convertedObj.goodsPriceCode = convertedObj.goodsCode;
        }
        if (type === '3') {
            convertedObj.itemType = '3'
            convertedObj.goodsPriceCode = convertedObj.packageCode;
            delete convertedObj.packageCode;
        }

        delete convertedObj.mathType;
        delete convertedObj.type;
        delete convertedObj.attachment;
        delete convertedObj.orgCode;
        delete convertedObj.goodsFlavor;
        delete convertedObj.isEstmClear;
        delete convertedObj.mainAttachment;

        return convertedObj;
    });
    // postForm.payType = '1'
    calculateOrderQty(comDetail.value)
    console.log(comDetail.value);
    confirmSignshow.value = true
    // return
    // postForm.totalAmt = postForm.detail.reduce((sum, item) => sum + Number(item.salePrice), 0)
}



</script>
<style scoped lang="scss">
.certificate-container {
  .certificate-header {
    padding: 29px 0px 50px 0px;
    text-align: center;
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #cccccc;
    line-height: 16px;
  }

  .certificate-main {
    width: 200px;
    height: 200px;
    margin: 0 auto;
    background-image: url("@/assets/images/open/i_certificate_qrcode.png");
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
  }

  .certificate-footer {
    margin-top: 100px;
    text-align: center;
    margin: 50px 38px 0 38px;
    background: #665f52;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .certificate-footer-input {
      width: 190px;
      background: #665f52;
      border-radius: 4px;
      padding-left: 15px;
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffaa00;
      line-height: 16px;
    }

    .certificate-footer-input::placeholder {
      color: #807766;
    }
  }
}
.change-type{
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 13px;
    color: #FFFFFF;
    line-height: 13px;
    padding-top: 40px;
    padding-right: 10px;
    text-align: right;
  }
.tabs-list-box {
  margin-top: 10px;
  padding-left: 20px;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  .list-item {
    margin-right: 20px;
    // width: 150px; 
    flex-basis: 25%;
    height: 40px;
    font-size: 16px;
    border-radius: 10px;
    line-height: 40px;
    text-align: center;
    color: #fff;
    background-color: #3d3d4c;
  }
  .active {
    background-color: #ffaa00;
    color: #fff !important;
  }
}
.popup-block {
  .popup-block-main {
    padding: 20px 24px 10px 24px;
    .main-item{
      height: 40px;
      background: #404047;
      border-radius: 8px;
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 16px;
      color: #FFFFFF;
      line-height: 40px;
      padding-left: 12px;
      margin-bottom: 10px;
      &.select{
        border: 1px solid #FFDD99;
      }
    }
  }
  .popup-block-footer {
    padding: 10px 24px 20px 24px;
    .button-group {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
.roomName{
  font-size: 32px;
  text-align: center;
  color: #ffffff;
  padding-top: 30px;
}
</style>
